/**
 * 申请退款弹窗,暂时废弃，改用comm下的refund.tsx
 */
import React, { useEffect, useRef, useState } from 'react';
import { Descriptions, Modal, Divider, Button } from 'antd'
import { getOnceOrderDetail, updateOnceOrderStatus } from '@/services/order/api';
import { MsgType, showMsg } from '@/utils/utils';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';

const Refund: React.FC<any> = (props) => {
  const { record = {}, handleModalVisible, optCallback } = props;
  const [errorCount, setErrorCount] = useState(0); // 没用上？
  //  一次性订单详情
  const [detail, setDetail] = useState<ORDERAPI.OnceOrderItem>({});
  // 选择的行
  const [selectedRows, setSelectedRows] = useState<STOCKGOODSAPI.GoodsItem[]>([]);
  // 退款金额
  const [refundAmount, setRefundAmount] = useState<number>(0);
  const actionRef = useRef();
  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '品牌',
      dataIndex: 'brand_name',
      editable: false
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      editable: false
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      editable: false
    },
    {
      title: '单品折扣',
      dataIndex: 'goods_price',
      editable: false
    },
    {
      title: '折扣价',
      dataIndex: 'goods_price',
      editable: false
    },
    {
      title: '订单折扣',
      dataIndex: 'goods_price',
      editable: false
    },
    {
      title: '退款数量',
      dataIndex: 'goods_num',
      valueType: 'digit',
      fieldProps: {
        precision: 0,
        min: 1,
      },
      editable: (e, e1) => e1.goods_id !== '10086',
      formItemProps: (myForm, record) => {
        // console.log('数量', form.getFieldsValue());
        // console.log('record', record);
        const cur = detail.order_goods_list[record.rowIndex];
        return {
          rules: [{ required: true, message: '此项为必填项' },
            { validator: (e, val) => {
              if (val < 1 || val > cur.goods_num) {
                setErrorCount(errorCount + 1);
                return Promise.reject(new Error(`最多可退${cur.goods_num}!`)); 
              } else {
                setErrorCount(errorCount - 1);
              }
              return Promise.resolve();
            }, message: `最多可退${cur.goods_num}!`},
          ],
          onBlur: (e) => countChange(e.target.value, cur, record, myForm, 'blur'),
          onChange: (e) => countChange(e.target.value, cur, record, myForm, 'change'),
        };
      },
    },
    {
      title: '退款金额',
      dataIndex: 'goods_price'
    }
  ]

  useEffect(() => {
    if (record.order_id) {
      getOnceOrderDetail(record.order_id).then((data) => {
        setDetail(data);
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      });
    }
  }, [record]);

  useEffect(() => {
    selectedRows.forEach(item => {
      setRefundAmount((prev) => {
        return prev + Number(item.goods_price);
      });
    });
  }, [selectedRows]);

  // 数量变化、失去焦点
  const countChange = (val, cur, record, myForm, type) => {
    val = parseFloat(val);
    // 输入为正整数，才计算金额
    console.log('aaa', val, Math.sign(val) === -1, Number.isInteger(val), Math.sign(val) === -1 || !Number.isInteger(val))
    if (Math.sign(val) === -1 || !Number.isInteger(val)) {
      if (type === 'change') {
        return;
      }
      val = parseFloat(parseFloat(val).toFixed(0));
    }
    if (Math.sign(val) === 1 && Number.isInteger(val)) {
      const tar = myForm.getFieldsValue()[record.rowKey];
      console.log('orderObj1111', orderObj)
      const dj = parseFloat(orderObj.discount_ratio) === 0 ? 0.01 : parseFloat(cur.goods_price) * parseFloat(orderObj.discount_ratio);
      console.log('blue', dj, val, record.rowIndex, record.rowKey, myForm.getFieldsValue());
      console.log('cur', cur);
      console.log('tar', tar);
      if (tar.goods_num <= cur.goods_num) {
        tar.refundPrice = parseFloat(dj * val).toFixed(2); // 最多可退
        orderObj.order_goods_list[record.rowIndex].maxRefund = tar.refundPrice;
      }
      myForm.setFieldsValue({ [record.rowKey]: tar });
      setOrderObj(orderObj);
      actionRef.current && actionRef.current?.reload();
      getTotalPrice();
    }
  }

  // 计算总金额
  const getTotalPrice = () => {
    setTimeout(() => {
      console.log('getTotalPrice-selectedRowKeys', selectedRow, editForm.getFieldsValue());
      let price = 0;
      let maxprice = 0;
      // eslint-disable-next-line no-restricted-syntax
      for (const key in editForm.getFieldsValue()) {
        const element = editForm.getFieldsValue()[key];
        // console.log('element', element)
        price = parseFloat(price + parseFloat(element.refundPrice));
      }
      selectedRow.forEach(element => {
        maxprice = parseFloat(maxprice + parseFloat(element.goods_price || element.goods_total_price));
      });
      console.log('price11111', maxprice);
      if (parseFloat(price) > 0) {
        form.setFieldsValue({ total: price.toFixed(2) });
        orderObj.maxrefund = parseFloat(price);
        setOrderObj(orderObj);
      }
    }, 100);
  }
  const updateOrderStatus = async (order_status: string) => {
    if (selectedRows.length === 0) {
      showMsg('请选择退款商品', MsgType.INFO);
      return
    }
    console.log(selectedRows);
    try {
      const refund_order_goods_list = selectedRows.map(item => {
        return {
          brand_id: item.brand_id,
          brand_name: item.brand_name,
          goods_id: item.goods_id,
          goods_name: item.goods_name,
          goods_num: item.goods_num,
          goods_price: item.goods_price,
          goods_total_price: item.goods_total_price,
          order_id: record.order_id,
          record_id: item.record_id,
          specs_id: item.specs_id,
          specs_name: item.specs_name
        }
      })
      const data = {
        order_id: record.order_id as string,
        order_status,
        refund_order_goods_list,
        refund_price: refundAmount
      };
      await updateOnceOrderStatus(data);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  return <Modal
      title="订单退款"
      width="90%"
      maskClosable={false}
      onCancel={() => handleModalVisible(false)}
      footer={[
        <Button key="close" onClick={() => {
          handleModalVisible(false);
        }}>
          关闭
        </Button>,
        <Button key="pay" type="primary" onClick={ async () => {
          const success = await updateOrderStatus('A');
          if (success) {
            handleModalVisible(false);
            optCallback && optCallback({
              type: 3
            })
          }
        }}>
          提交审批
        </Button>
      ]}
      visible>
      <div className="dialog">
        <div style={{fontSize: 12}}>1.患者信息</div>
        <Divider />
        <Descriptions>
          <Descriptions.Item label="身份证/住院号">
            {detail.identity_no || detail.admission_num}
          </Descriptions.Item>
          <Descriptions.Item label="患者姓名">
            {detail.patient_name}
          </Descriptions.Item>
          <Descriptions.Item label="患者性别">{detail.patient_sex_name || '-'}</Descriptions.Item>
          <Descriptions.Item label="归属科室">
            {detail.create_dept_name}
          </Descriptions.Item>
        </Descriptions>
       
        <div style={{marginBottom: 10, fontSize: 12}}>2.选择退款商品</div>
        <Divider />

        <EditableProTable<STOCKGOODSAPI.GoodsItem> 
          rowKey="record_id"
          actionRef={actionRef}
          columns={columns}
          search={false}
          options={false}
          editable={{
            type: 'multiple'
          }}
          rowSelection={{
            columnWidth: 60,
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRows(selectedRows);
            },
            onSelect: (record, selected, selectedRows, nativeEvent) => {
              console.log(record, selected, selectedRows, nativeEvent);
              actionRef.current.startEditable(record.record_id);
            }
          }}
          recordCreatorProps={false}
          pagination={false}
          scroll={{ x: 1000 }}
          value={detail.order_goods_list}
          dataSource={detail.order_goods_list}
          bordered />

        <div style={{marginBottom: 10, marginTop: 10, fontSize: 12}}>3.退款结算信息</div>
        <Divider />
        <Descriptions>
          <Descriptions.Item label="订单支付金额">
            <span style={{
              fontWeight: 'bold',
              color: '#333'
            }}>{detail.sett_price}</span> （元）
          </Descriptions.Item>
          <Descriptions.Item label="退款商品数量">
            <span style={{
              fontWeight: 'bold',
              color: '#F5232D'
            }}>{selectedRows.length}</span>（件）
          </Descriptions.Item>
          <Descriptions.Item label="退款金额">
            <span style={{
              fontWeight: 'bold',
              color: '#F5232D'
            }}>{refundAmount}</span> （元）
          </Descriptions.Item>
        </Descriptions>
      </div>
    </Modal>
}
export default Refund;
